package matlap.database.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import matlap.database.ConnectionManager;
import matlap.database.dao.DeadlineDAO;

import matlap.shared.Deadline;

public class DeadlineJdbcDAO implements DeadlineDAO {

	Connection con = null;
	Statement st = null;
	ResultSet rs = null;

	public List<Deadline> getDeadlines() {
		try {
			ConnectionManager.initConnection();
			con = ConnectionManager.createConnection();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		List<Deadline> list = new ArrayList<Deadline>();
		String volume;
		String deadline;
		String query = "SELECT Volume,Deadline FROM deadlines ";
		try {
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery(query);
			int i = 0;

			while (rs.next()) {

				volume = rs.getString("Volume");
				deadline = rs.getString("Deadline");
				Deadline deadl = new Deadline();
				deadl.setDeadline(deadline);
				deadl.setVolume(volume);
				list.add(i, deadl);
				i++;

			}

		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		} finally {
			try {
				ConnectionManager.closeConnection(con);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return list;
	}

	public int getDeadlinesNumber() {
		try {
			ConnectionManager.initConnection();
			con = ConnectionManager.createConnection();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		int nr = 0;
		String query = "SELECT COUNT(volume) AS volume FROM deadlines";
		try {
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery(query);
			while (rs.next()) {
				nr = Integer.parseInt(rs.getString("volume"));
			}
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		} finally {
			try {
				ConnectionManager.closeConnection(con);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return nr;
	}

}
